package com.linked.basemanage.base.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.linked.basemanage.base.bean.param.BaseInfoPageParam;
import com.linked.basemanage.base.bean.po.BaseInfoPO;
import com.linked.basemanage.base.service.IBaseService;
import com.linked.universal.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @author :dbq
 * @date : 2022/11/22 16:02
 */
@RestController
@RequestMapping("base")
public class BaseController {

    private final String baseSetting = "BASESETTING";

    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    private final IBaseService baseService;

    private final RedisTemplate redisTemplate;

    @Autowired
    public BaseController(IBaseService baseService, RedisTemplate redisTemplate) {
        this.baseService = baseService;
        this.redisTemplate = redisTemplate;
    }

    @PostMapping("queryBaseInfoPage")
    Result queryBaseInfoPage(@RequestBody BaseInfoPageParam param) {

        IPage<BaseInfoPO> result = null;
        try {
            result = baseService.queryBaseInfoPage(param);
        } catch (Exception e) {
            logger.error("查询基础信息页面接口异常！", e);
            Result.error("查询基础信息页面接口异常！");
        }
        return Result.success(result);
    }

    @PostMapping("saveBaseInfo")
    Result saveBaseInfo(@RequestBody BaseInfoPO param) {
        boolean ret = false;
        try {
            ret = baseService.saveBaseInfo(param);
        } catch (Exception e) {
            logger.error("保存基础配置接口异常！", e);
            return Result.error("保存基础配置接口异常！");
        }
        return ret ? Result.ok(true,"保存成功！") : Result.ok(false,"保存失败！");
    }

    @PostMapping("findBaseSetting")
    String findBaseSetting(@RequestParam String baseKey) {
        //如果redis中存在，则从redis中取
        if (redisTemplate.opsForHash().hasKey(baseSetting, baseKey)) {
            return (String) redisTemplate.opsForHash().get(baseSetting, baseKey);
        } else {

            BaseInfoPO temp = null;
            try {
                temp = baseService.findBaseInfo(baseKey);
            } catch (Exception e) {
                logger.error("查找基础信息接口异常！", e);
            }
            if (temp != null) {
                redisTemplate.opsForHash().put(baseSetting, baseKey, temp.getBaseValue());
                return temp.getBaseValue();
            }
        }
        return null;
    }
}
